package com.kdx.cloud.common.domain;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import com.kdx.cloud.common.runtime.Login;
import com.kdx.cloud.common.runtime.LoginManager;
import com.kdx.cloud.common.tools.ResultMsg;
import com.kdx.cloud.common.utils.cookieUtil;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;

/**
 * @author litianshen
 * @date 2017年2月17日 下午8:21:29
 * @Description:
 */
@Data
@Slf4j
public class AccessInfo {
	private String userId;
	private String token;
	private String url;
	private String method;

	public static final String NOTLOGIN = "notlogin";
	public static final String OUTlOGIN = "outlogin";
	public static final String NOTPERMISSION = "notpermission";

	/**
	 * @param userId
	 * @param token
	 * @param url
	 * @param method
	 */
	public AccessInfo(HttpServletRequest request) {
		super();
		this.url = request.getRequestURI();// api/ad-user/role/{roleId}/restful?aa==1
		this.method = request.getMethod();
		this.userId = cookieUtil.getCookie(request, "userId");
		this.token = cookieUtil.getCookie(request, "token");

		String userName = cookieUtil.getCookie(request, "username");
		try {
			if(!StringUtils.isEmpty(userName)){
				userName = URLDecoder.decode(userName, "UTF-8");
			}
		} catch (UnsupportedEncodingException e) {
			log.error("", e);
		}
		Login login = new Login();
		login.setUserId(this.userId);
		login.setUserName(userName);
		LoginManager.setLogin(login);
	}

	public AccessInfo() {
		super();
	}

	public boolean checkIsLogin(HttpServletResponse response) throws IOException {
		if (StringUtils.isEmpty(this.userId) || StringUtils.isEmpty(this.token)) {
			response.getWriter().write("{'access':'"+NOTLOGIN+"'}");
			return false;
		}
		return true;
	}

	public boolean checkByRest(HttpServletResponse response, RestTemplate restTemplate) throws IOException {
		if (!checkIsLogin(response)) {
			return false;
		}
		HttpEntity<AccessInfo> requestEntity = new HttpEntity<AccessInfo>(this);
		ResponseEntity<ResultMsg> entity = restTemplate.exchange("http://ad-user/backgroud/access", HttpMethod.POST,
				requestEntity, ResultMsg.class);
		ResultMsg checkResult = entity.getBody();
		return handleResponse(response, checkResult);
	}
	
	public boolean handleResponse(HttpServletResponse response,ResultMsg resultMsg) throws IOException {
		if (!resultMsg.isSuccess()) {
			response.getWriter().write("{'access':'"+resultMsg.getMessage()+"'}");
		}
		return resultMsg.isSuccess();
	}

}
